//
//  USChatController+IM.m
//  us
//
//  Created by lhx on 2025/4/7.
//

#import "USChatController+IM.h"

@implementation USChatController (IM)

- (void)initConversation {
    NSLog(@"conversationId == %@",self.conversationId);
    self.conversation = [EMClient.sharedClient.chatManager getConversation:self.conversationId type:EMConversationTypeChat createIfNotExist:YES];

    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
        
    [self loadMessagesWithCompletion:^(NSArray<EMChatMessage *> *messages, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshMsg:messages isInsertBottom:NO isScrollBottom:YES animated:NO];
        });
    }];
    
    [[EMClient sharedClient].chatManager markAllConversationsAsRead];//将所有会话的未读消息数清零
    
    UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.allObjects.firstObject;
    SceneDelegate *sceneDelegate = (SceneDelegate *)scene.delegate;
    [sceneDelegate updateChatBadge:0];
}


#pragma mark - EMChatManagerDelegate
- (void)messagesDidReceive:(NSArray *)aMessages{
    // 收到消息，遍历消息列表。
    NSString *conId = self.conversation.conversationId;
    
    NSMutableArray *addMsgs = [NSMutableArray array];
    for (EMChatMessage *message in aMessages) {
        if (![conId isEqualToString:message.conversationId]) {
            continue;
        }
        
        NSLog(@"message.body  =  %@",message.ext);
        if ([message.ext.allKeys containsObject:@"us_system"]) {
            if ([message.ext[@"us_system"] boolValue]  == YES) {
                //系统消息不显示并且删除
                [self.conversation removeMessagesFromServerMessageIds:@[message.messageId] completion:^(EMError * _Nullable aError) {
                    if (aError) {
                        NSLog(@"删除失败 -- %@",aError.errorDescription);
                    }
                }];
                continue;
            }
        }
        [addMsgs addObject:message];
        [self m_sendReadReceipt:message];
        [self.conversation markMessageAsReadWithId:message.messageId error:nil];
        
        [USEMRemindManager remindMessage:message];
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        [self refreshMsg:addMsgs isInsertBottom:YES isScrollBottom:YES];
     });
}
- (void)messagesInfoDidRecall:(NSArray<EMRecallMessageInfo *> * _Nonnull)aRecallMessagesInfo{
    
    NSLog(@"--- 对方撤回消息");
    [aRecallMessagesInfo enumerateObjectsUsingBlock:^(EMRecallMessageInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        EMRecallMessageInfo *recallMessageInfo = (EMRecallMessageInfo *)obj;
        EMChatMessage *message = recallMessageInfo.recallMessage;
                
        [self.messageList enumerateObjectsUsingBlock:^(USMessageViewModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.message.messageId isEqualToString:message.messageId]) {
                
                
                EMCustomMessageBody *body = [[EMCustomMessageBody alloc]initWithEvent:@"recall" customExt:@{@"recallBy":recallMessageInfo.recallBy}];
                EMChatMessage *recallMsg = [[EMChatMessage alloc]initWithConversationID:self.conversation.conversationId from:message.from to:message.to body:body ext:nil];
                
                recallMsg.chatType = (EMChatType)self.conversation.type;
                recallMsg.isRead = YES;
                recallMsg.localTime = message.localTime;
                recallMsg.timestamp = message.timestamp;
                [self.conversation insertMessage:recallMsg error:nil];
                
                USMessageViewModel *model = [USMessageViewModel new];
                model.message = recallMsg;
                [self.messageList replaceObjectAtIndex:idx withObject:model];
                
            }
            
        }];
    }];
    
    [self.tableView reloadData];
    
}

 
- (void)dealloc{
    [[EMClient sharedClient].chatManager removeDelegate:self];
}

#pragma mark - 获取历史消息
- (void)loadMessagesWithCompletion:(void(^)(NSArray <EMChatMessage *>*messages, NSError *error))completion {
    EMConversation *conversation = self.conversation;
     
    NSArray<EMChatMessage *> *messages = [conversation loadMessagesStartFromId:self.moreMsgId count:30 searchDirection:EMMessageSearchDirectionUp];
    
    !completion?:completion(messages,nil);
    
}


#pragma mark - public method
- (void)m_sendText:(NSString *)aText {
    if ([aText length] == 0) {
        return;
    }
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:aText];
    [self sendMessageWithBody:body ext:nil];

}

- (void)m_sendImageData:(NSData *)aImageData size:(CGSize)size{
     
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:aImageData displayName:@""];
    body.size = size;
    [self sendMessageWithBody:body ext:nil];
    
}

- (void)m_sendImageWithaFilePath:(NSString *)filePath{

    EMImageMessageBody *body =[[EMImageMessageBody alloc]initWithLocalPath:filePath displayName:@""];
    [self sendMessageWithBody:body ext:nil];
    
}

//发送表情图片
- (void)m_sendEmjoWithEmjoName:(NSString *)emjoName {
    EMCustomMessageBody *body = [[EMCustomMessageBody alloc]initWithEvent:@"emoji" customExt:@{@"localName":emjoName,@"imgUrl":@""}];
    
    [self sendMessageWithBody:body ext:nil];
}

- (void)m_sendVoiceWithFilePath:(NSString *)filePath
                     timeLength:(NSInteger)aTimeLength
                        volumes:(NSArray *)volumes{
    
    EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc]initWithLocalPath:filePath displayName:@""];
    body.duration = (int)aTimeLength;
    if(body.duration < 1){
        [self.view makeToast:@"说话时间太短"];
        return;
    }
    
    // 构造扩展字段
    NSDictionary *ext = @{
        @"volumes": volumes ?: @[] // 把音量数组传进去
    };
    // 发送消息
    [self sendMessageWithBody:body ext:ext];
    
}

- (void)m_sendReadReceipt:(EMChatMessage *)msg{
    if ([self _isNeedSendReadAckForMessage:msg isMarkRead:NO]) {
        [[EMClient sharedClient].chatManager sendMessageReadAck:msg.messageId toUser:msg.conversationId completion:nil];
    }
}

//发送消息体
- (void)sendMessageWithBody:(EMMessageBody *)aBody
                        ext:(NSDictionary * __nullable)aExt{
 
    
    NSDictionary *pushObject = @{
       //设置推送模板名称。
       //若为默认模板 `default`，无需传入模板名称。若为自定义模板，需传入模板名称。
        @"name":@"nickname",
    };
    
    NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:aExt];
    [ext setValue:pushObject forKey:@"em_push_template"];
 
    
    EMChatMessage *message = [[EMChatMessage alloc]initWithConversationID:self.conversation.conversationId body:aBody ext:ext];
   
     message.chatType = (EMChatType)self.conversation.type;

    [self sendMsgimpl:message];
  
    if (USUser.user.chatDays == 0) {
        [self updateChatDays];
    }
}

- (void)updateChatDays{
    NSInteger chatDays = (NSInteger)[[NSDate date] timeIntervalSince1970];

    NSDictionary *params = @{
        @"chatDays" : @(chatDays)
    };

    [[EMNetWork shareManager] em_post:API_EditUser
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        [self.view endEditing:YES];
        
        if (!api.success) {
            return;
        }
        USUser *user = [USUser user];
        user.chatDays = chatDays;
        [USUser saveUser:user];
         
    } fail:^{
                
    }];
}
- (void)sendMsgimpl:(EMChatMessage *)message{

    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self insertSendMsg:message];
    });
    @weakify(self)
    [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMChatMessage *message, EMError *error) {
        @strongify(self)
        [self msgStatusDidChange:message error:error];
        if (error) {
            [self.view makeToast:error.errorDescription];
        }
    }];
}

- (void)m_deleteMessage:(EMChatMessage *)message
             Completion:(void(^)(void))completion{
    [[EMClient sharedClient].chatManager removeMessagesFromServerWithConversation:self.conversation messageIds:@[message.messageId] completion:^(EMError * _Nullable aError) {
        if (!aError) {
            !completion?:completion();
        }
    }];
}

///撤回消息
- (void)m_recallMessage:(EMChatMessage *)message
             Completion:(void(^)(void))completion {
    [[EMClient sharedClient].chatManager recallMessageWithMessageId:message.messageId completion:^(EMError * _Nullable aError) {
        if (!aError) {
            !completion?:completion();
        }else{
            NSLog(@"撤回失败 -- %@",aError.errorDescription);
        }
    }];
}

#pragma mark - 已读回执
- (BOOL)_isNeedSendReadAckForMessage:(EMChatMessage *)aMessage
                          isMarkRead:(BOOL)aIsMarkRead{
    if (aMessage.direction == EMMessageDirectionSend || aMessage.isReadAcked || aMessage.chatType != EMChatTypeChat)
        return NO;
    EMMessageBody *body = aMessage.body;
    if (!aIsMarkRead && (body.type == EMMessageBodyTypeFile || body.type == EMMessageBodyTypeVoice || body.type == EMMessageBodyTypeImage))
        return NO;
//    if (body.type == EMMessageBodyTypeText && [((EMTextMessageBody *)body).text isEqualToString:EMCOMMUNICATE_CALLED_MISSEDCALL] && aMessage.direction == EMMessageDirectionReceive)
//        return NO;
        
    return YES;
}



@end
